import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Input,
  Card,
  Form,
  Message,
  Popconfirm,
  Select,
  Badge,
  Avatar,
  Tag,
  Switch,
  DatePicker,
  Grid,
  Radio,
  PaginationProps,
  Space,
} from '@arco-design/web-react';
import { IconSearch, IconRefresh } from '@arco-design/web-react/icon';

import styles from '../style/index.module.less';
import '../mock';
import '../../categories/mock';
import '../../tags/mock';
import {
  getList,
  remove,
  updateStatus,
  updatePublishStatus,
  updateCollectStatus,
} from '@/api/articles';
import dayjs from 'dayjs';
import { getTagsList } from '@/api/tags';
import { getCategoriesList } from '@/api/categories';
import { useHistory } from 'react-router-dom';

const publishStatusOptions = [
  {
    key: '1',
    value: '已发布',
  },
  {
    key: '2',
    value: '未发布',
  },
];
const statusOptions = [
  {
    key: '1',
    value: '启用',
  },
  {
    key: '2',
    value: '停用',
  },
];
const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
function Articles() {
  const { Row, Col } = Grid;
  const { useForm } = Form;
  const [form] = useForm();
  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});
  const [tagsArr, setTagsArr] = useState([]);
  const [categoriesArr, setCategoriesArr] = useState([]);
  const history = useHistory();

  const columns: any = [
    {
      title: '文章标题',
      dataIndex: 'title',
      fixed: 'left',
    },

    {
      title: '封面',
      dataIndex: 'cover',
      render: (_, record: any) => {
        return (
          <Avatar shape="square">
            <img src={record.cover} />
          </Avatar>
        );
      },
    },
    {
      title: '简介',
      dataIndex: 'introduction',
    },
    {
      title: '分类',
      dataIndex: 'categories',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      render: (_, record) => {
        let result = [];
        for (let i = 0; i < record.tags.length; i += 3) {
          result.push(record.tags.slice(i, i + 3)); // i=0 0-3 i=3 3-6
        }
        return result.map((item, index) => {
          return (
            <div style={{ marginBottom: 10 }} key={index}>
              {item.map((sub) => (
                <Tag style={{ marginRight: 10 }} key={sub}>
                  {sub}
                </Tag>
              ))}
            </div>
          );
        });
      },
    },
    {
      title: '查看/评论/点赞/收藏	',
      dataIndex: 'views',
      render: (_, record) => {
        return `${record.views}/${record.comment}/${record.like}/${record.collect}`;
      },
    },
    {
      title: '文章状态',
      dataIndex: 'status',
      render: (_, record: any) => {
        return (
          <Switch
            checkedText="启用"
            uncheckedText="停用"
            checked={record.status === 1}
            onChange={(checked) => onStatusChange(checked, record)}
          />
        );
      },
    },
    {
      title: '发布状态',
      dataIndex: 'publishStatus',
      render: (_, record) => {
        const texts = {
          1: '已发布',
          2: '未发布',
        };
        const enums = {
          1: 'success',
          2: 'error',
        };
        return (
          <Badge
            status={enums[record.publishStatus]}
            text={texts[record.publishStatus]}
          />
        );
      },
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (_, record) => {
        return dayjs(record.createTime * 1000).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      render: (_, record) => {
        return record.updateTime
          ? dayjs(record.updateTime * 1000).format('YYYY-MM-DD HH:mm:ss')
          : '-';
      },
    },

    {
      title: '操作',
      dataIndex: 'operations',
      fixed: 'right',
      width: 200,
      render: (_, record) => (
        <div className={styles.operations}>
          <div>
            <Button
              onClick={() => onChangePublishStatus(record)}
              type="text"
              size="small"
            >
              {record.publishStatus === 1 ? '下线' : '发布'}
            </Button>
            <Button onClick={() => onView(record)} type="text" size="small">
              查看
            </Button>
          </div>
          {record.publishStatus === 2 && (
            <div>
              <Button onClick={() => onUpdate(record)} type="text" size="small">
                修改
              </Button>
              <Popconfirm title="确认删除?" onOk={() => onDelete(record)}>
                <Button type="text" status="danger" size="small">
                  删除
                </Button>
              </Popconfirm>
            </div>
          )}
        </div>
      ),
    },
  ];

  //   获取标签
  const getTags = () => {
    getTagsList({
      page: 1,
      pageSize: 9999,
    }).then((res: any) => {
      const list = res.data.list?.map((item) => {
        item.key = item._id;
        item.value = item.name;
        return item;
      });
      setTagsArr(list);
    });
  };

  //获取分类
  const getCategories = async () => {
    const res: any = await getCategoriesList({
      page: 1,
      pageSize: 9999,
    });
    const list = res.data.list?.map((item) => {
      item.key = item._id;
      item.value = item.name;
      return item;
    });
    const temp = [
      {
        key: '',
        value: '全部',
      },
      ...list,
    ];
    setCategoriesArr(temp);
  };

  // 发布状态修改(下线，发布)
  const onChangePublishStatus = async (record) => {
    setLoading(true);
    const postData = {
      id: record._id,
      publishStatus: record.publishStatus === 1 ? 2 : 1,
    };
    const res: any = await updatePublishStatus(postData);
    if (res.code === 0) {
      Message.success(res.msg);
      fetchData();
    } else {
      Message.error('文章状态修改失败，请重试！');
      setLoading(false);
    }
  };

  // 查看
  const onView = (record) => {};

  // 文章状态修改
  const onStatusChange = async (checked, record) => {
    setLoading(true);
    const postData = {
      id: record._id,
      status: checked ? 1 : 2,
    };
    const res: any = await updateStatus(postData);
    if (res.code === 0) {
      Message.success(res.msg);
      fetchData();
    } else {
      Message.error('文章状态修改失败，请重试！');
      setLoading(false);
    }
  };

  //   修改文章
  const onUpdate = (row) => {
    history.push(`/blog/articles/edit?id=${row._id}`);
  };

  const onDelete = async (row) => {
    setLoading(true);
    const res: any = await remove({
      id: row._id,
    });
    if (res.code === 0) {
      Message.success(res.msg);
      fetchData();
    } else {
      Message.error('删除失败，请重试！');
      setLoading(false);
    }
  };

  // 一键操作
  const handleUpdateCollectStatus = async (isCollect) => {
    setLoading(true);
    const res: any = await updateCollectStatus({
      isCollect,
    });
    if (res.code === 0) {
      Message.success(res.msg);
      fetchData();
    } else {
      Message.error('一键操作失败，请重试！');
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  useEffect(() => {
    getTags();
    getCategories();
  }, []);

  // 获取表格数据
  async function fetchData() {
    console.log(pagination);
    const { current, pageSize } = pagination;
    setLoading(true);
    const params = {
      page: current,
      pageSize,
      ...formParams,
    };
    try {
      const res: any = await getList(params);
      console.log(res);
      if (res.code === 200) {
        setData(res.data.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.total,
        });
        setLoading(false);
      } else {
      }
    } catch (error) {
      console.error(error);
    }
  }

  //   分页
  function onChangeTable(pagination) {
    setPatination(pagination);
  }

  //   搜索
  function onSearch() {
    console.log(form.getFields());
    setFormParams(form.getFields());
  }

  // 重置
  const onReset = () => {
    form.resetFields();
  };
  return (
    <div>
      <Card
        title="文章列表"
        headerStyle={{ border: 'none', height: 'auto', paddingTop: '20px' }}
      >
        <div className={styles['search-form-wrapper']}>
          <Form
            form={form}
            initialValues={{
              categories: '',
              status: '0',
              publishStatus: '0',
            }}
            {...layout}
            style={{ marginBottom: 20 }}
            layout="horizontal"
          >
            <Row>
              <Col span={6}>
                <Form.Item field="title" label="文章标题">
                  <Input placeholder="请输入文章标题" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item field="categories" label="分类">
                  <Select placeholder="请选择分类">
                    {categoriesArr &&
                      categoriesArr.map((item) => (
                        <Select.Option key={item.key} value={item.key}>
                          {item.value}
                        </Select.Option>
                      ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item field="tags" label="标签">
                  <Select mode="multiple" placeholder="请选择标签">
                    {tagsArr &&
                      tagsArr.map((item) => (
                        <Select.Option key={item.key} value={item.key}>
                          {item.value}
                        </Select.Option>
                      ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item field="status" label="文章状态">
                  <Select placeholder="请选择文章状态">
                    {[
                      {
                        key: '0',
                        value: '全部',
                      },
                      ...statusOptions,
                    ].map((item) => (
                      <Select.Option key={item.key} value={item.key}>
                        {item.value}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={6}>
                <Form.Item field="publishStatus" label="发布状态">
                  <Select placeholder="请选择文章发布状态" defaultValue="">
                    {[
                      {
                        key: '0',
                        value: '全部',
                      },
                      ...publishStatusOptions,
                    ].map((item) => (
                      <Select.Option key={item.key} value={item.key}>
                        {item.value}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item field="createTime" label="创建时间">
                  <DatePicker.RangePicker
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item field="updateTime" label="修改时间">
                  <DatePicker.RangePicker
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </Form.Item>
              </Col>
              <Col span={5} offset={1}>
                <Form.Item>
                  <div className={styles['right-button']}>
                    <Space>
                      <Button
                        type="primary"
                        icon={<IconSearch />}
                        onClick={onSearch}
                      >
                        查询
                      </Button>
                      <Button icon={<IconRefresh />} onClick={onReset}>
                        重置
                      </Button>
                    </Space>
                  </div>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles['button-group']}>
          <Space>
            <Radio.Group
              onChange={handleUpdateCollectStatus}
              type="button"
              name="lang"
              style={{ marginLeft: 20 }}
            >
              <Radio value={true}>一键开启收藏</Radio>
              <Radio value={false}>一键关闭收藏</Radio>
            </Radio.Group>
          </Space>
        </div>
        <Table
          rowKey="_id"
          loading={loading}
          onChange={onChangeTable}
          pagination={pagination}
          columns={columns}
          data={data}
          scroll={{ x: 1600 }}
        />
      </Card>
    </div>
  );
}

export default Articles;
